import React from 'react';
import { History, Location, LocationDescriptor } from '../history';
import RouterContext from './context';
import { ContextValue, Message } from './';
interface Props {

}
interface State {
  location: Location;
}
//在此组件里定义一个Location路径对象，然后通过上下文传递给它的子组件们
export default class extends React.Component<Props, State> {
    locationState: any
    state = {
      location: { // /a#/user window.location.hash=#/user /user
        pathname: window.location.hash.slice(1)
      }
    }
    componentDidMount() {
      window.addEventListener('hashchange', (event: HashChangeEvent) => {
        this.setState({
          location: {
            ...this.state.location,
            pathname: window.location.hash.slice(1) || '/',
            state: this.locationState
          }
        });
      });
      //如果没有这行代码，就没有默认的hash值
      window.location.hash = window.location.hash || '/';
    }
    render() {
      const that = this;//缓存this指针
      const history: History = {
        push(to: LocationDescriptor) {
          if (history.message) {
            const allow = window.confirm(history.message(typeof to === 'object' ? to as Location : { pathname: to }));
            if (!allow) return;
          }
          if (typeof to === 'object') {
            const { pathname, state } = to;
            that.locationState = state;//此这个时候先缓存location中的状态
            window.location.hash = pathname;
          } else {
            that.locationState = null;
            window.location.hash = to;
          }
        },
        message: null,
        block(message: Message | null) {
          history.message = message;
        }
      }
      const contextValue: ContextValue = {
        location: this.state.location,
        history
      }
      return (
        <RouterContext.Provider value={contextValue}>
          {this.props.children}
        </RouterContext.Provider>
      )
    }
}
